package com.aspire.aimini.controller;

import com.aspire.aimini.service.StatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 统计分析控制器
 *
 * @author wangguiyou
 * @date 2024-12-19
 */
@Slf4j
@RestController
@RequestMapping("/api/statistics")
@RequiredArgsConstructor
@Tag(name = "统计分析", description = "统计分析相关的API接口")
public class StatisticsController {

    private final StatisticsService statisticsService;

    /**
     * 获取用户统计信息
     *
     * @param userId 用户ID
     * @return 用户统计信息
     */
    @GetMapping("/user")
    @Operation(summary = "获取用户统计信息", description = "获取用户的统计信息")
    public ResponseEntity<Map<String, Object>> getUserStatistics(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取用户统计信息: userId={}", userId);

        Map<String, Object> statistics = statisticsService.getUserStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取系统统计信息
     *
     * @return 系统统计信息
     */
    @GetMapping("/system")
    @Operation(summary = "获取系统统计信息", description = "获取系统的统计信息")
    public ResponseEntity<Map<String, Object>> getSystemStatistics() {
        log.info("获取系统统计信息");

        Map<String, Object> statistics = statisticsService.getSystemStatistics();
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取热门标签统计
     *
     * @param limit 限制数量
     * @return 热门标签列表
     */
    @GetMapping("/tags/popular")
    @Operation(summary = "获取热门标签统计", description = "获取热门标签的统计信息")
    public ResponseEntity<List<Map<String, Object>>> getPopularTagsStatistics(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        log.info("获取热门标签统计: limit={}", limit);

        List<Map<String, Object>> statistics = statisticsService.getPopularTagsStatistics(limit);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取热门素材统计
     *
     * @param limit 限制数量
     * @return 热门素材列表
     */
    @GetMapping("/materials/popular")
    @Operation(summary = "获取热门素材统计", description = "获取热门素材的统计信息")
    public ResponseEntity<List<Map<String, Object>>> getPopularMaterialsStatistics(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        log.info("获取热门素材统计: limit={}", limit);

        List<Map<String, Object>> statistics = statisticsService.getPopularMaterialsStatistics(limit);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取热门文案统计
     *
     * @param limit 限制数量
     * @return 热门文案列表
     */
    @GetMapping("/copywritings/popular")
    @Operation(summary = "获取热门文案统计", description = "获取热门文案的统计信息")
    public ResponseEntity<List<Map<String, Object>>> getPopularCopywritingsStatistics(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        log.info("获取热门文案统计: limit={}", limit);

        List<Map<String, Object>> statistics = statisticsService.getPopularCopywritingsStatistics(limit);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取用户素材统计
     *
     * @param userId 用户ID
     * @return 用户素材统计
     */
    @GetMapping("/user/materials")
    @Operation(summary = "获取用户素材统计", description = "获取用户的素材统计信息")
    public ResponseEntity<Map<String, Object>> getUserMaterialStatistics(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取用户素材统计: userId={}", userId);

        Map<String, Object> statistics = statisticsService.getUserMaterialStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取用户文案统计
     *
     * @param userId 用户ID
     * @return 用户文案统计
     */
    @GetMapping("/user/copywritings")
    @Operation(summary = "获取用户文案统计", description = "获取用户的文案统计信息")
    public ResponseEntity<Map<String, Object>> getUserCopywritingStatistics(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取用户文案统计: userId={}", userId);

        Map<String, Object> statistics = statisticsService.getUserCopywritingStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取用户AI使用统计
     *
     * @param userId 用户ID
     * @return 用户AI使用统计
     */
    @GetMapping("/user/ai-usage")
    @Operation(summary = "获取用户AI使用统计", description = "获取用户的AI使用统计信息")
    public ResponseEntity<Map<String, Object>> getUserAiUsageStatistics(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取用户AI使用统计: userId={}", userId);

        Map<String, Object> statistics = statisticsService.getUserAiUsageStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 按类型统计素材
     *
     * @param userId 用户ID
     * @return 素材类型统计
     */
    @GetMapping("/materials/by-type")
    @Operation(summary = "按类型统计素材", description = "按文件类型统计素材数量")
    public ResponseEntity<Map<String, Long>> getMaterialStatisticsByType(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("按类型统计素材: userId={}", userId);

        Map<String, Long> statistics = statisticsService.getMaterialStatisticsByType(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 按类型统计文案
     *
     * @param userId 用户ID
     * @return 文案类型统计
     */
    @GetMapping("/copywritings/by-type")
    @Operation(summary = "按类型统计文案", description = "按内容类型统计文案数量")
    public ResponseEntity<Map<String, Long>> getCopywritingStatisticsByType(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("按类型统计文案: userId={}", userId);

        Map<String, Long> statistics = statisticsService.getCopywritingStatisticsByType(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 按类型统计AI使用
     *
     * @param userId 用户ID
     * @return AI使用类型统计
     */
    @GetMapping("/ai-usage/by-type")
    @Operation(summary = "按类型统计AI使用", description = "按服务类型统计AI使用次数")
    public ResponseEntity<Map<String, Long>> getAiUsageStatisticsByType(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("按类型统计AI使用: userId={}", userId);

        Map<String, Long> statistics = statisticsService.getAiUsageStatisticsByType(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取每日上传统计
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param userId    用户ID
     * @return 每日上传统计
     */
    @GetMapping("/daily/uploads")
    @Operation(summary = "获取每日上传统计", description = "获取指定时间范围内的每日上传统计")
    public ResponseEntity<Map<String, Long>> getDailyUploadStatistics(
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取每日上传统计: startDate={}, endDate={}, userId={}", startDate, endDate, userId);

        Map<String, Long> statistics = statisticsService.getDailyUploadStatistics(startDate, endDate, userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取每日生成统计
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param userId    用户ID
     * @return 每日生成统计
     */
    @GetMapping("/daily/generations")
    @Operation(summary = "获取每日生成统计", description = "获取指定时间范围内的每日生成统计")
    public ResponseEntity<Map<String, Long>> getDailyGenerationStatistics(
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取每日生成统计: startDate={}, endDate={}, userId={}", startDate, endDate, userId);

        Map<String, Long> statistics = statisticsService.getDailyGenerationStatistics(startDate, endDate, userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取每日使用统计
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param userId    用户ID
     * @return 每日使用统计
     */
    @GetMapping("/daily/usage")
    @Operation(summary = "获取每日使用统计", description = "获取指定时间范围内的每日使用统计")
    public ResponseEntity<Map<String, Long>> getDailyUsageStatistics(
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取每日使用统计: startDate={}, endDate={}, userId={}", startDate, endDate, userId);

        Map<String, Long> statistics = statisticsService.getDailyUsageStatistics(startDate, endDate, userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取每日消耗统计
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param userId    用户ID
     * @return 每日消耗统计
     */
    @GetMapping("/daily/consumption")
    @Operation(summary = "获取每日消耗统计", description = "获取指定时间范围内的每日消耗统计")
    public ResponseEntity<Map<String, Object>> getDailyConsumptionStatistics(
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取每日消耗统计: startDate={}, endDate={}, userId={}", startDate, endDate, userId);

        Map<String, Object> statistics = statisticsService.getDailyConsumptionStatistics(startDate, endDate, userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取用户活跃度统计
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 用户活跃度统计
     */
    @GetMapping("/user-activity")
    @Operation(summary = "获取用户活跃度统计", description = "获取用户活跃度统计信息")
    public ResponseEntity<Map<String, Object>> getUserActivityStatistics(
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        log.info("获取用户活跃度统计: startDate={}, endDate={}", startDate, endDate);

        Map<String, Object> statistics = statisticsService.getUserActivityStatistics(startDate, endDate);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取存储使用统计
     *
     * @param userId 用户ID
     * @return 存储使用统计
     */
    @GetMapping("/storage/usage")
    @Operation(summary = "获取存储使用统计", description = "获取存储使用统计信息")
    public ResponseEntity<Map<String, Object>> getStorageUsageStatistics(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取存储使用统计: userId={}", userId);

        Map<String, Object> statistics = statisticsService.getStorageUsageStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取系统性能统计
     *
     * @return 系统性能统计
     */
    @GetMapping("/system/performance")
    @Operation(summary = "获取系统性能统计", description = "获取系统性能统计信息")
    public ResponseEntity<Map<String, Object>> getSystemPerformanceStatistics() {
        log.info("获取系统性能统计");

        Map<String, Object> statistics = statisticsService.getSystemPerformanceStatistics();
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取用户排行榜
     *
     * @param type  排行类型
     * @param limit 限制数量
     * @return 用户排行榜
     */
    @GetMapping("/leaderboard")
    @Operation(summary = "获取用户排行榜", description = "获取用户排行榜")
    public ResponseEntity<List<Map<String, Object>>> getUserLeaderboard(
            @Parameter(description = "排行类型") @RequestParam String type,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        log.info("获取用户排行榜: type={}, limit={}", type, limit);

        List<Map<String, Object>> leaderboard = statisticsService.getUserLeaderboard(type, limit);
        return ResponseEntity.ok(leaderboard);
    }

    /**
     * 获取AI服务使用统计
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return AI服务使用统计
     */
    @GetMapping("/ai-service/usage")
    @Operation(summary = "获取AI服务使用统计", description = "获取AI服务使用统计信息")
    public ResponseEntity<Map<String, Object>> getAiServiceUsageStatistics(
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        log.info("获取AI服务使用统计: startDate={}, endDate={}", startDate, endDate);

        Map<String, Object> statistics = statisticsService.getAiServiceUsageStatistics(startDate, endDate);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取错误统计
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 错误统计
     */
    @GetMapping("/errors")
    @Operation(summary = "获取错误统计", description = "获取系统错误统计信息")
    public ResponseEntity<Map<String, Object>> getErrorStatistics(
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        log.info("获取错误统计: startDate={}, endDate={}", startDate, endDate);

        Map<String, Object> statistics = statisticsService.getErrorStatistics(startDate, endDate);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取用户增长统计
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 用户增长统计
     */
    @GetMapping("/user-growth")
    @Operation(summary = "获取用户增长统计", description = "获取用户增长统计信息")
    public ResponseEntity<Map<String, Object>> getUserGrowthStatistics(
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        log.info("获取用户增长统计: startDate={}, endDate={}", startDate, endDate);

        Map<String, Object> statistics = statisticsService.getUserGrowthStatistics(startDate, endDate);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取收入统计
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 收入统计
     */
    @GetMapping("/revenue")
    @Operation(summary = "获取收入统计", description = "获取收入统计信息")
    public ResponseEntity<Map<String, Object>> getRevenueStatistics(
            @Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        log.info("获取收入统计: startDate={}, endDate={}", startDate, endDate);

        Map<String, Object> statistics = statisticsService.getRevenueStatistics(startDate, endDate);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 生成统计报告
     *
     * @param request 报告请求
     * @param userId  用户ID
     * @return 报告ID
     */
    @PostMapping("/report/generate")
    @Operation(summary = "生成统计报告", description = "生成统计报告")
    public ResponseEntity<Map<String, Object>> generateStatisticsReport(
            @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("生成统计报告: userId={}", userId);

        String reportType = (String) request.get("reportType");
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate startDate = LocalDate.parse((String) request.get("startDate"));
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate endDate = LocalDate.parse((String) request.get("endDate"));
        String format = (String) request.get("format");

        String reportId = statisticsService.generateStatisticsReport(reportType, startDate, endDate, format, userId);

        Map<String, Object> result = Map.of(
                "reportId", reportId,
                "message", "统计报告生成中",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 导出统计数据
     *
     * @param request 导出请求
     * @param userId  用户ID
     * @return 导出文件
     */
    @PostMapping("/export")
    @Operation(summary = "导出统计数据", description = "导出统计数据")
    public ResponseEntity<byte[]> exportStatisticsData(
            @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("导出统计数据: userId={}", userId);

        String dataType = (String) request.get("dataType");
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate startDate = LocalDate.parse((String) request.get("startDate"));
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate endDate = LocalDate.parse((String) request.get("endDate"));
        String format = (String) request.get("format");

        byte[] data = statisticsService.exportStatisticsData(dataType, startDate, endDate, format, userId);

        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=statistics." + format)
                .header("Content-Type", "application/octet-stream")
                .body(data);
    }

    /**
     * 获取实时统计数据
     *
     * @param userId 用户ID
     * @return 实时统计数据
     */
    @GetMapping("/realtime")
    @Operation(summary = "获取实时统计数据", description = "获取实时统计数据")
    public ResponseEntity<Map<String, Object>> getRealtimeStatistics(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取实时统计数据: userId={}", userId);

        Map<String, Object> statistics = statisticsService.getRealtimeStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 刷新统计缓存
     *
     * @param cacheKey 缓存键
     * @return 刷新结果
     */
    @PostMapping("/cache/refresh")
    @Operation(summary = "刷新统计缓存", description = "刷新统计缓存")
    public ResponseEntity<Map<String, Object>> refreshStatisticsCache(
            @Parameter(description = "缓存键") @RequestParam(required = false) String cacheKey) {
        log.info("刷新统计缓存: cacheKey={}", cacheKey);

        statisticsService.refreshStatisticsCache(cacheKey);

        Map<String, Object> result = Map.of(
                "cacheKey", cacheKey != null ? cacheKey : "all",
                "message", "统计缓存刷新成功",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }
}